<template>
  <div class="aqi-trend">
    <div class="chart-container">
      <v-chart class="chart" :option="chartOption" autoresize />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,defineProps,watch } from 'vue'
import { use } from "echarts/core"
import { CanvasRenderer } from "echarts/renderers"
import { LineChart } from "echarts/charts"
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from "echarts/components"
import VChart from "vue-echarts"

// 注册必需的组件
use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
])

const chartOption = ref({
  title: {
    text: 'AQI 24小时变化趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    formatter: '{b}<br />AQI: {c}'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    boundaryGap: false
  },
  yAxis: {
    type: 'value',
    name: 'AQI'
  },
  series: [{
    name: 'AQI',
    type: 'line',
    data: [],
    smooth: true,
    lineStyle: {
      width: 2
    },
    itemStyle: {
      color: '#4CAF50'
    },
    areaStyle: {
      color: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [{
          offset: 0,
          color: 'rgba(76,175,80,0.3)'
        }, {
          offset: 1,
          color: 'rgba(76,175,80,0.1)'
        }]
      }
    }
  }]
})

const props = defineProps({
  area:{
    type:String,
    required:true,
    default:"惠州市"
  }
})

// 模拟获取24小时数据
const fetchTrendData = async (area) => {
  try {
    // 这里替换为实际的API调用
    const response = await fetch("http://127.0.0.1:8765/aqi_trend", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        area: area
      })
    })
    
    const result = await response.json()
    if (result.status === 0 && result.data.rows.length > 0) {
      const formattedData = result.data.rows.map(row => ({
        ...row,
        time_point:new Date(row.time_point*1000).toLocaleDateString("zh-CN",{month: "2-digit",day: "2-digit",hour: "2-digit"}) //将时间戳转换为小时
      }))
      updateChartData(formattedData)
    }
  } catch (error) {
    console.error("获取趋势数据失败", error)
  }
}

const updateChartData = (data) => {
  const hours = data.map(item => item.time_point)
  const values = data.map(item => item.AQI)
  
  chartOption.value.xAxis.data = hours
  chartOption.value.series[0].data = values
}

onMounted(() => {
  fetchTrendData()
})

watch(() => props.area, (newValue) => {
  fetchTrendData(newValue)
})
</script>

<style scoped>
.aqi-trend {
  background-color: white;
  height: 310px;
  border-radius: 8px;
  margin: 0 5px 15px 5px;
  padding: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-container {
  width: 100%;
  height: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}
</style> 